/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "mod_share_client.h"

namespace sleepyface
{
    namespace arch
    {
        namespace modules
        {
            ShareClient::ShareClient() : ArchModule()
            {
                setName("share-client");
            }

        	ModuleValue ShareClient::get(string k0, string k1, Architecture &a)
        	{
        		z_data *rtn = (z_data *)malloc(sizeof(z_data));
        		*rtn = z_share_client_pull(&clients[k0].second, atoi(k1.c_str()));
        		return ModuleValue(ModuleValue::_data, rtn);
        	}

        	ModuleValue ShareClient::set(string k0, string k1, ModuleValue v, Architecture &a)
        	{
        		z_data res = z_share_client_push(&clients[k0].second, atoi(k1.c_str()), (z_data *)v.getData());
        		if (!z_data_eq(&res, (z_data *)v.getData()))
        			return ModuleValue();
        		return v;
        	}

        	int ShareClient::signal(ModuleSignal s, Architecture &a)
        	{
        		if (s.getCode() == signalConnect)
        		{
        			z_ipc_client tmp = z_ipc_client_init_global((char *)s.getData(1).getString().c_str(), s.getData(2).getInt());
        			if (z_ipc_client_connect(&tmp) != 0)
        				return 1;
        			z_share_client tmp2 = z_share_client_init(&tmp);
        			pair<z_ipc_client, z_share_client> p;
        			p.first = tmp;
        			p.second = tmp2;
        			clients[s.getData(0).getString()] = p;
        			return 0;
        		}
        		else if (s.getCode() == signalDisconnect)
        		{
        			z_ipc_client_disconnect(&clients[s.getData(0).getString()].first);
        			z_ipc_client_release(clients[s.getData(0).getString()].first);
        			z_share_client_release(clients[s.getData(0).getString()].second);
        			return 0;
        		}
        		else
        		{
        			return 0;
        		}
        	}
		}
	}
}
